<template>
    <div id="box">
        <input type="text" v-model="content" @keyup.enter="sent">
        <ul>
            <li v-for="(data, index) in datas" :key="data.id">
                <input type="checkbox" v-model="data.ischecked">
                <span :class="data.ischecked ? 'text' : ''">{{ data.content }}</span>
                <button @click="del(index)">删除</button>
            </li>
        </ul>
        <div id="footer">
            <input type="checkbox" v-model="checkedAll">
            <span>{{ numberSelect }}</span>
            <span>{{ datas.length }}</span>
            <span @click="delAll">清除已完成任务</span>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
let content = ref('')
let datas = ref([])
// 挂载后将本地存储的数据渲染到页面上
onMounted(() => {
    let comment = JSON.parse(localStorage.getItem('comments')) || []
    datas.value = comment
})
// 回车添加待办事项
const sent = () => {
    datas.value.push({ id: Date.now(), ischecked: false, content: content.value })
    content.value = ''
}
// 删除单个待办事项
const del = (index) => {
    if (datas.value[index].ischecked === true) {
        if (confirm('确认删除吗')) {
            datas.value.splice(index, 1)
        }
    }
}
// 删除已完成的待办事项 
const delAll = () => {
    let newDatas = datas.value.filter((data) => !data.ischecked)
    datas.value = newDatas
}
// 全选框
const checkedAll = computed({
    get() {
        return datas.value.every((data) => data.ischecked)
    },
    set(status) {
        datas.value.forEach((data) => {
            data.ischecked = status
        })
    }
})
// 计算已完成的待办事项的数量
const numberSelect = computed(() => {
    return datas.value.filter((data) => data.ischecked).length
})
// 监听datas的数据变化，将数据存入本地存储
watch(datas, (newV) => {
    localStorage.setItem('comments', JSON.stringify(newV))
}, { deep: true })
</script>

<style lang="scss" scoped>
* {
    margin: 0;
    padding: 0;
    list-style-type: none;
    box-sizing: border-box;
}

#box {
    width: 172px;
}

ul li,
#footer {
    display: flex;
    justify-content: space-between;
}

.text {
    color: #ccc;
    text-decoration: line-through;
}
</style>